import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var textStr = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width, //充满屏幕宽度,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center, //居中
          children: [
            SizedBox(
              height: 50,
            ),
            RaisedButton(
              child: Text("二维码扫描"),
              onPressed: () {
                getQrcodeState().then((value) => setState(() {
                      this.textStr = value;
                    }));
              },
            ),
            SizedBox(
              height: 20,
            ),
            Text("扫描内容为${this.textStr}"),
          ],
        ),
      ),
    );
  }

  //扫描二维码
  static Future<String> getQrcodeState() async {
    try {
      const ScanOptions options = ScanOptions(
        strings: {
          'cancel': '取消',
          'flash_on': '开启闪光灯',
          'flash_off': '关闭闪光灯',
        },
      );
      final ScanResult result = await BarcodeScanner.scan(options: options);
      return result.rawContent;
    } catch (e) {}
    return "";
  }
}
